package com.sanq.product.books.controller;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.BooksShelfVo;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.service.BooksShelfService;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/app/books_shelf")
public class BooksShelfController {

    @Resource
    private BooksShelfService booksShelfService;
    @Resource
    private JedisPoolService jedisPoolService;

    @LogAnnotation(description = "删除数据")
    @DeleteMapping(value = "/delete")
    public Response deleteById(HttpServletRequest request, @RequestBody BooksShelfVo booksShelfVo) {

        int result = booksShelfService.delete(booksShelfVo);
        return result == 1 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "查询所有数据")
    @GetMapping(value = "/all")
    public Response findList(HttpServletRequest request, BooksShelfVo booksShelfVo) {

        UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(booksShelfVo.getToken())), UsersVo.class);

        booksShelfVo.setUserId(usersVo.getId());

        List<BooksShelfVo> list = booksShelfService.findList(booksShelfVo);
        return list != null ? new Response().success(list) : new Response().failure();
    }

    @LogAnnotation(description = "保存到书架")
    @PostMapping(value = "/save")
    public Response add(HttpServletRequest request, @RequestBody BooksShelfVo booksShelfVo) {

        UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(booksShelfVo.getToken())), UsersVo.class);

        booksShelfVo.setUserId(usersVo.getId());

        int result = booksShelfService.save(booksShelfVo);

        return result == 1 ? new Response().success() : new Response().failure();
    }

}